package com.haide.channel.pro.util;


import com.haide.channel.pro.constant.CharacterDict;
import com.haide.channel.pro.constant.ConfigDict;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 请求渠道工具类
 * <p>
 * 1.
 * </p>
 *
 * @author : wukong
 * @version : 1.0.0
 * @date : 2018/7/18
 */
@Slf4j
@NoArgsConstructor
public final class RequestUtil {

    /**
     * base64加密数据集
     *
     * @param obj
     * @return
     */
    public static String base64Data(Object obj) {
        String jsonStr = JsonUtil.toJSONString(obj);
        log.info("HaiDe-请求参数:{}", jsonStr);
        return SecurityUtil.base64Encode(jsonStr);
    }

    /**
     * urlEncode By Data
     *
     * @param base64Str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String urlEncode(String base64Str) throws UnsupportedEncodingException {
        return URLEncoder.encode(base64Str, CharacterDict.UTF_8);
    }

    /**
     * 获取签名
     *
     * @param base64Str
     * @return
     */
    public static String getSign(String base64Str) {
        String sign = SecurityUtil.md5DesEncrypt("data=" + base64Str + "&key=" + ConfigDict.KEY + "");
        log.info("HaiDe-签名:{}", sign);
        return sign;
    }

    public static String jointUrl(String url, String... args) {
        String jointUrl = String.format(url, args);
        log.info("HaiDe-请求url:{}", jointUrl);
        return jointUrl;
    }

    /**
     * 请求渠道
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getUrl(Object obj, String sourceUrl) throws UnsupportedEncodingException {
        String base64Data = RequestUtil.base64Data(obj);
        String urlEncode = RequestUtil.urlEncode(base64Data);
        String sign = RequestUtil.getSign(base64Data);
        String url = RequestUtil.jointUrl(sourceUrl, sign, ConfigDict.AGENT_NO, urlEncode);
        return url;
    }
}
